// 1. 引入 express
const express = require("express")

// 2. 创建应用对象
const app = express()

// 3. 设置路由规则
app.get("/server", (request, response) => {
    // 设置响应头 设置允许跨域
    response.setHeader("Access-Control-Allow-Origin", "*")
    // 设置响应体
    response.send("Hello Ajax GET!")
})

app.post("/server", (request, response) => {
    // 设置响应头 设置允许跨域
    response.setHeader("Access-Control-Allow-Origin", "*")
    // 设置响应体
    response.send("Hello Ajax POST!")
})

app.all("/server-json", (request, response) => {
    // 设置响应头 设置允许跨域
    response.setHeader("Access-Control-Allow-Origin", "*")
    // 设置响应头
    response.setHeader("Access-Control-Allow-Headers", "*")

    const student = {
        name: "blue",
        age: 19,
        sex: "boy"
    }

    // 设置响应体
    response.send(JSON.stringify(student))
})

// 延迟响应
app.get("/delay", (request, response) => {
    // 设置响应头 设置允许跨域
    response.setHeader("Access-Control-Allow-Origin", "*")
    setTimeout(() => {
        // 设置响应体
        response.send("延迟响应!")
    }, 3000)
})

// jquery
app.all("/jquery", (request, response) => {
    // 设置响应头 设置允许跨域
    response.setHeader("Access-Control-Allow-Origin", "*")
    const blue = {
        name: "Blue",
        age: 19,
        sex: "Boy"
    }
    response.send(JSON.stringify(blue))
})

// axios
app.all("/axios", (request, response) => {
    // 设置响应头 设置允许跨域
    response.setHeader("Access-Control-Allow-Origin", "*")
    const blue = {
        name: "Blue",
        age: 19,
        sex: "Boy"
    }
    response.send(JSON.stringify(blue))
})

// 4.监听端口启动服务
app.listen(8000, () => {
    console.log("服务已经启动, 8000 端口监听中")
})